package cn.wubo.mybatis.plus.dynamic.datasource.demo.core;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChangeDataSourceService {

    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    public boolean changeDS(String datasourceId) {
        //切到默认数据源
        DynamicDataSourceContextHolder.clear();
        //找到所有的配置
        List<DataSourceDTO> dataSourceList = new ArrayList<>() {{
            add(new DataSourceDTO("33", "jdbc:mysql://10.140.40.33:3306/qfc_lowcode_be?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true", "MySql", "com.mysql.cj.jdbc.Driver", "zzyys", "MysqlZzyys2022!"));
            add(new DataSourceDTO("174", "jdbc:mysql://10.133.92.174:3307/lowcode?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8", "MySql", "com.mysql.cj.jdbc.Driver", "root", "jszx@2022"));
        }};

        if (!CollectionUtils.isEmpty(dataSourceList)) {
            for (DataSourceDTO dataSource : dataSourceList) {
                if (dataSource.getDatasourceid().equals(datasourceId)) {
                    System.out.println("已找到数据源,datasourceId是：" + dataSource.getDatasourceid());
                    //判断连接是否存在，不存在就创建
                    dynamicRoutingDataSource.checkCreateDataSource(dataSource);
                    //切换数据源
                    DynamicDataSourceContextHolder.push(dataSource.getDatasourceid());
                    return true;
                }
            }
        }
        return false;
    }
}
